﻿using System;
using System.Collections.Generic;
using System.Text;

using ET;
using Marx;
using Marx.Utils;

namespace Server
{
    [ObjectSystem]
    public class WeeklyRefreshAwakeSystem : AwakeSystem<WeeklyRefreshComponent, DayOfWeek, TimeSpan>
    {
        //weekday: 1-7
        public override void Awake(WeeklyRefreshComponent self, DayOfWeek weekday, TimeSpan timePoint)
        {
            self.Awake(weekday, timePoint);
        }
    }


    public class WeeklyRefreshComponent : Entity, IAwake<DayOfWeek, TimeSpan>
    {
        public TimeSpan RefreshTimePoint => refreshTimePoint_;
        public DayOfWeek WeekDay => weekDay_;

        private TimeSpan refreshTimePoint_;
        private DayOfWeek weekDay_;
        private RefreshTimer timer_;

        public void Awake(DayOfWeek day, TimeSpan point)
        {
            weekDay_ = day;
            refreshTimePoint_ = point;

            timer_ = new RefreshTimer();
            Start();
        }

        private void Start()
        {
            TimeSpan during = TimeUtils.GetRefreshTimeSpanFromNow(weekDay_, refreshTimePoint_);
            timer_.StartRefreshTimer(during,
                TimeSpan.FromDays(7),
                () => Game.EventSystem.Publish(new EventType.WeeklyRefresh() { Domain = this.DomainScene() })).Coroutine();
        }

        public override void Dispose()
        {
            if(IsDisposed)
            {
                return;
            }

            base.Dispose();
            timer_.Cancel();
        }
    }
}
